﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyHelper;
using clf.weighing.entity;


namespace weighing
{

    public class MaterialDao : BaseDao<Material>
    {
        #region instance

        private static MaterialDao? instance;
        public static MaterialDao Instance => instance ??= new MaterialDao();

        public override string GetTableName()
        {
            return TableName.material.ToString();
        }
        #endregion
        public List<Material> GetList()
        {
            string condition = MaterialField.belong.ToString() + $" = {(int)DataBelong.Enterprise}";            
            condition += $" and ({MaterialField.affiliated_company_id}= {App.CurrentCompanyVo?.Id??0} or {MaterialField.affiliated_company_id} = 0  )";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition);
            var data = Sqlite.Select<Material>(sql);
            return data;
        }

        public List<Material> SelectByNameOrFirstCaseLike(String queryStr)
        {
            if (queryStr.IsNullOrEmpty()) return null;
            string condition = MaterialField.belong.ToString() + $" = {(int)DataBelong.Enterprise}";            
            condition += $" and ({MaterialField.first_case} like '%{queryStr}%' Or {MaterialField.name} like '%{queryStr}%')";
            condition += $" and ({MaterialField.affiliated_company_id}= {App.CurrentCompanyVo.Id} or {MaterialField.affiliated_company_id}= 0  )";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), null, condition);
            var data = Sqlite.Select<Material>(sql);
            return data;
        }

        public bool IsExist(Material material)
        {
            if (material.categoryId == null) material.categoryId = 0;
            String condition = $" ({MaterialField.id} = {material.id}) or ({MaterialField.name} = '{material.name}'" +
                $" and {MaterialField.category_id} = {material.categoryId} " +
                $" and {MaterialField.belong} = {(int)DataBelong.Enterprise}" +
                $" and {MaterialField.affiliated_company_id} = {App.CurrentCompanyVo.Id} )";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), "id", condition, null, null, null, 1, 0);
            var data = Sqlite.Select<Material>(sql);
            return data.IsNotNullOrEmpty();
        }

        public bool IsExist(string name)
        {
            String condition = MaterialField.name.ToString() + $" = '{name}'";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), "id", condition, null, null, null, 1, 0);
            var data = Sqlite.Select<Material>(sql);
            return data.IsNotNullOrEmpty();
        }

        /// <summary>
        /// 是否是属于政府数据
        /// </summary>
        /// <param name="material"></param>
        /// <returns></returns>
        public bool IsGovernment(Material material)
        {
            String condition = $"{MaterialField.id} = {material.id} and {MaterialField.belong} = {(int)DataBelong.Government}";
            String sql = SqlBuilder.GetSelectSql(GetTableName(), "id", condition, null, null, null, 1, 0);
            var data = Sqlite.Select<Material>(sql);
            return data.IsNotNullOrEmpty();
        }


        public int DeleteMaterial(Material material, Boolean isTrue = false)
        {
            if (material == null)
            {
                return 0;
            }
            if (WeighingBillDao.Instance.IsMaterialHasBill(material.id))
            {
                return -1;
            }
            if (isTrue)
            {
                return Sqlite.Delete(material, isTrue);
            }
            else
            {
                String condition = MaterialField.id.ToString() + $" = {material.id}";
                String time = DateTimeHelper.getCurrentDateTime();
                String set = MaterialField.update_time.ToString() + $" = '{time}'"
                        + $", {MaterialField.is_delete} = 1 "
                        + $", {MaterialField.delete_time} = '{time}'"
                        + $", {MaterialField.update_user_name} = '{App.CurrentUser.name}'"
                        + $", {MaterialField.update_user_id} = {App.CurrentUser.id}";
                String sql = SqlBuilder.GetUpdateSql(GetTableName(), set, condition);

                String PriceSet = MaterialPriceField.delete_time.ToString() + $" = '{time}'"
                       + $", {MaterialPriceField.is_delete} = 1 "
                       + $", {MaterialPriceField.delete_time} = '{time}'";

                String PriceCondition = MaterialPriceField.material_id.ToString() + $" = {material.id}";
                string tablename = MaterialPriceDao.Instance.GetTableName();
                string priceSql = SqlBuilder.GetUpdateSql(tablename, PriceSet, PriceCondition);
                string[] sqls = new string[] { sql, priceSql };
                int res = Sqlite.TransactionExecute(sqls);
                return res;
            }

        }

        /// <summary>
        /// 操作下载 的数据
        /// </summary>
        /// <param name="materal"></param>
        /// <returns></returns>
        public int InsertOrUpdateServerData(Material materal)
        {
            if (materal == null) return 0;
            if (IsExist(materal))
            {
                materal.firstCase = MyHelper.StringHelper.GetFirstPinyin(materal.name);
                return Sqlite.Update(materal);
            }
            else
            {
                materal.firstCase = MyHelper.StringHelper.GetFirstPinyin(materal.name);
                return Sqlite.Insert(materal);
            }
        }
        /// <summary>
        ///  过磅时 保存物资信息
        /// </summary>
        /// <param name="material"></param>
        public void AutoSaveMatrial(Material? material)
        {
            if (material == null) return;
            if (!IsExist(material))
            {
                Sqlite.Insert(material);
            }
        }

        public int InsertMaterialAutoCreaterPrice(Material material)
        {
            if (material.addTime == null) material.addTime = DateTime.Now;
            string insertSql = SqlBuilder.GetInsertSql(material);

            MaterialPrice inPrice = new MaterialPrice()
            {
                id = IdHelper.LongID,
                materialId = material.id,
                materialName = material.name,
                type = (int)MaterialPriceType.Buy,
                addTime = material.addTime,
                effectiveTime = material.addTime,
                failureTime = material.addTime.Value.AddYears(1),
                belong = (int)DataBelong.Enterprise,
                isDelete = 0,
                price = 0,
                status = 1
            };
            string inpricesql = SqlBuilder.GetInsertSql(inPrice);
            MaterialPrice outPrice = new MaterialPrice()
            {
                id = IdHelper.LongID + 1,
                materialName = material.name,
                materialId = material.id,
                type = (int)MaterialPriceType.Sale,
                addTime = material.addTime,
                effectiveTime = material.addTime,
                failureTime = material.addTime.Value.AddYears(1),
                belong = (int)DataBelong.Enterprise,
                isDelete = 0,
                price = 0,
                status = 1
            };
            string outpricesql = SqlBuilder.GetInsertSql(outPrice);
            string[] sqls = new string[] { insertSql, inpricesql, outpricesql };
            return Sqlite.TransactionExecute(sqls);
        }

        public Material? FindByName(string name)
        {
            String condition = MaterialField.name.ToString() + $" = '{name}'";
            String sql = SqlBuilder.GetSelectSqlWithSoftDeleteCondition(GetTableName(), "id", condition, null, null, null, 1, 0);
            var data = Sqlite.Select<Material>(sql);
            return data.FirstOrDefault();
        }

        public int CountAll(string key = "")
        {
            string condition = $"{MaterialField.name} like '%{key}%' and {MaterialField.is_delete} = 0 ";
            string sql = SqlBuilder.GetSelectSql(GetTableName(), $"{MaterialField.id}", condition);
            var data = Sqlite.Select<Material>(sql);
            return data != null ? data.Count : 0;
        }

        public List<Material> SelectPage(int pageindex = 1, int size = 20, string key = "")
        {
            string condition = $"{MaterialField.name} like '%{key}%' and {MaterialField.is_delete} = 0 ";
            int limit = size;
            int offsert = (pageindex - 1) * limit;
            string sql = SqlBuilder.GetSelectSql(GetTableName(), null, condition, null, null, null, limit, offsert);
            var data = Sqlite.Select<Material>(sql);
            return data;
        }
    }
}